package com.wva.common.utils;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Author: hong
 * @Date: 2025/2/27 13:13:02
 */
public class CustomObjectMapper extends ObjectMapper{
    public CustomObjectMapper() {
        deserializeIgnoreUnknownProperties();
        deserializeBottomLine2Camel();
        deserializeEnableTimeSupport();
    }

    public CustomObjectMapper(String timeFormat) {
        deserializeIgnoreUnknownProperties();
        deserializeBottomLine2Camel();
        deserializeCustomTimeFormat(timeFormat);
    }

    /**
     * 导入time module以支持local datetime解析
     */
    private void deserializeEnableTimeSupport() {
        registerModule(new JavaTimeModule());
    }

    /**
     * json下划线属性映射到实体驼峰属性
     */
    private void deserializeBottomLine2Camel() {
        setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    }

    /**
     * 反序列化时忽略目标类型存在但json不存在的属性<br> <a href="https://www.jianshu.com/p/9def74f3d2f7">...</a>
     */
    private void deserializeIgnoreUnknownProperties() {
        configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * 反序列化时自定义时间格式
     * @param timeFormat
     */
    private void deserializeCustomTimeFormat(String timeFormat) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(timeFormat);
        JavaTimeModule module = new JavaTimeModule();
        module.addDeserializer(
                LocalDateTime.class,
                new LocalDateTimeDeserializer(formatter)
        );
        registerModule(module);
    }
}
